#!/usr/bin/env python
#-*- coding:utf-8 -*-

#file: L0Q2.py

import sys

def multiply_matrices(matrix1, matrix2):
    colunas_m1 = len(matrix1[0])
    linhas_m1 = len(matrix1)
    colunas_m2 = len(matrix2[0])
    linhas_m2 = len(matrix2)

    if colunas_m1 != linhas_m2:
        return -1

    product = []

    for i in range(linhas_m1):
        line =[]
        for j in range(colunas_m2):
            value = 0
            for k in range(colunas_m1):
                value += (matrix1[i][k] * matrix2[k][j])

            line.append(value)

        product.append(line)

    return product


def read_input(filename="L0Q2.in"):
    f = open(filename, "r")
    lines = f.readlines()
    f.close()

    matrices = []
    pair = []
    i = 0
    lines_num = len(lines)
    while i < lines_num:
        rows, columns = [int(n) for n in lines[i].split(' ')]

        m1 = []
        for l in range(rows):
            i += 1
            m1.append([int(n) for n in lines[i].split(' ')])

        pair.append(m1)

        i += 1
        if i < lines_num and lines[i].strip() == '':
            i += 1

        if len(pair) == 2:
            matrices.append(pair)
            pair = []

    return matrices


def write_output(matrix):
    try:
        for row in matrix:
            for item in row:
                print item,
            print
    except TypeError, e:
        print matrix

    print

def main():
    if len(sys.argv) > 1:
        input_file = sys.argv[1]
    else:
        input_file = sys.argv[0]
        start = input_file.rfind('/') + 1
        end = input_file.rfind('.py')
        input_file = input_file[start:end] + '.in'

    try:
        input = read_input(input_file)
    except IOError, e:
        print 'Arquivo de entrada "%s" nao encontrado.' % \
                input_file
        sys.exit(1)

    i = 0
    for pair in input:
        i += 1
        m1, m2 = pair
        m3 = multiply_matrices(m1, m2)

        print 'Conjunto #%d' % i
        write_output(m3)

if __name__ == '__main__':
    main()
